<?php

// 直接アクセスを拒否する
if (!defined("IN_APP"))
	exit("直接アクセスはできません。");

// ログインしたユーザーのみがアクセスできる
if (!isset($_SESSION['twitter_username']))
	exit("ログインしないとアクセスできません。");

require_once("Twitter/list_tweets.php");

function getHistoryResults($connect, $group_id, $type, $dateStart, $dateEnd, $user) {
	global $MESSAGES;

	// リーダーのidを取得する
	$leader_id = getLeaderId($connect, $group_id);
	$group_name = getGroupName($connect, $group_id);
	
	// リーダーのリストの本日のツイートを取得する
	try {
		$tweets = getTweetListForSpan($leader_id, $group_name, $dateStart, $dateEnd);
	} catch (Error $e) {
		return;
	}

	$found = array();

	// 挙手ツイートを探す
	foreach ($tweets as $tweet) {
		//　ユーザー指定なら、他のユーザーを飛ばす
		if (!empty($user)) {
			if ($user != $tweet->author_id) {
				continue;
			}
		}
		
		// 挙手を検索
		if (strpos($tweet->text, "【{$group_name}】【挙手】") === 0) {
			if ($type == "check" || $type == "all") {
				$tweet->comment = mb_trim(str_replace("【{$group_name}】【挙手】", "", $tweet->text));
				$tweet->type = "挙手";
				$tweet->name = getUserName($connect, $group_id, $tweet->author_id);
				array_push($found, $tweet);
			}
		}
		// アンケートを検索
		else if (strpos($tweet->text, "【{$group_name}】【アンケート】") === 0) {
			if ($type == "vote" || $type == "all") {
				$tweet->comment = mb_trim(str_replace("【{$group_name}】【アンケート】", "", $tweet->text));
				$tweet->type = "アンケート";
				$tweet->name = getUserName($connect, $group_id, $tweet->author_id);
				array_push($found, $tweet);
			}
		}
	}
	
	return $found;
}

// 履歴の検索をajaxで返す
function ajaxHistoryResults() {
	$_SESSION['history_type'] = $type = $_POST['type'];
	$_SESSION['history_start_date'] = $dateStart = strtotime($_POST['date_start']);
	$_SESSION['history_end_date'] = $dateEnd = strtotime($_POST['date_end']);
	$_SESSION['history_user'] = $user = $_POST['user'];
	
	$group_id = $_SESSION['group'];
	$connect = connectToDb();
	
	$results = getHistoryResults($connect, $group_id, $type, $dateStart, $dateEnd, $user);

	$output = "";
	
	foreach ($results as $result) {
		$output .= $result->type . "|";
		$output .= $result->id . "|";
		$output .= $result->icon . "|";
		$output .= $result->name . "|";
		$output .= $result->author . "|";
		$output .= date("Y年m月d日", $result->date) . "|";
		$output .= date("H:i", $result->date) . "|";
		$output .= $result->comment . "\n";
	}
	
	echo $output;
}
?>